package com.jvyou.mybatis.builder.parser;

import com.jvyou.mybatis.builder.config.PluginConfig;
import com.jvyou.mybatis.exception.JvyouMybatisException;
import com.jvyou.mybatis.utils.string.StringUtils;
import org.dom4j.Element;

import java.util.List;

/**
 * @author 橘柚
 * @version 1.0-SNAPSHOT
 * @Date 2024/7/20 11:41
 * @Description 插件节点处理器
 */
public class PluginsNodeHandler implements XmlConfigNodeHandler {
    @SuppressWarnings("unchecked")
    @Override
    public void handle(Element element, XmlConfigContext context) {
        List<Element> pluginEls = element.elements(PLUGIN);
        pluginEls.forEach(pluginEl -> {
            handlePlugin(pluginEl, context);
        });

    }

    @SuppressWarnings("unchecked")
    private void handlePlugin(Element pluginEl, XmlConfigContext context) {
        String id = pluginEl.attributeValue(ID);
        if (StringUtils.isEmpty(id)) {
            throw new JvyouMybatisException("插件节点的id属性不能为空");
        }
        String interceptor = pluginEl.attributeValue(INTERCEPTOR);
        if (StringUtils.isEmpty(interceptor)) {
            throw new JvyouMybatisException("插件节点的interceptor属性不能为空");
        }
        PluginConfig pluginConfig = new PluginConfig(id, interceptor);
        List<Element> propertyEls = pluginEl.elements(PROPERTY);
        propertyEls.forEach(propertyEl -> {
            String name = propertyEl.attributeValue(NAME);
            String value = propertyEl.attributeValue(VALUE);
            if (StringUtils.isEmpty(name)) {
                throw new JvyouMybatisException("插件节点的property节点的name属性不能为空");
            }
            if (StringUtils.isEmpty(value)) {
                throw new JvyouMybatisException("插件节点的property节点的value属性不能为空");
            }
            pluginConfig.putProperty(name, value);
        });
        context.addPlugin(pluginConfig);
    }
}
